Unary Operators

WHEN X AND +X ARE NOT EQUAL


In [1]:
import decimal

In [2]:
ctx = decimal.getcontext()

In [3]:
ctx.prec = 40

In [4]:
one_third = decimal.Decimal('1') / decimal.Decimal('3')

In [5]:
one_third


Out[5]:
Decimal('0.3333333333333333333333333333333333333333')

In [6]:
one_third == +one_third


Out[6]:
True

In [7]:
ctx.prec = 28

In [8]:
one_third == +one_third


Out[8]:
False

In [9]:
+one_third


Out[9]:
Decimal('0.3333333333333333333333333333')

In [10]:
from collections import Counter

In [11]:
ct = Counter('abracadabra')

In [12]:
ct


Out[12]:
Counter({'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2})

In [14]:
ct['r'] = -3

In [15]:
ct['d'] = 0

In [16]:
ct


Out[16]:
Counter({'a': 5, 'b': 2, 'c': 1, 'd': 0, 'r': -3})

In [18]:
+ct


Out[18]:
Counter({'a': 5, 'b': 2, 'c': 1})

Overloading + for Vector Addition


In [1]:
from array import array
import reprlib
import math
import numbers
import functools
import operator
import itertools

class Vector:
    typecode = 'd'
    
    def __init__(self, components):
        self._components = array(self.typecode, components)
        
    def __iter__(self):
        return iter(self._components)
    
    def __repr__(self):
        components = reprlib.repr(self._components)
        components = components[components.find('['):-1]
        return 'Vector({})'.format(components)
    
    def __str__(self):
        return str(tuple(self))
    
    def __bytes__(self):
        return (bytes([ord(self.typecode)]) +
               bytes(self._components))
    
    def __eq__(self, other):
        if isinstance(other, Vector):
            return (len(self) == len(other) and
                    all(a == b for a, b in zip(self, other)))
        else:
            return NotImplemented
    
    def __hash__(self):
        hashes = (hash(x) for x in self._components)
        return functools.reduce(operator.xor, hashes, 0)
    
    def __abs__(self):
        return math.sqrt(sum(x * x) for x in self)
    
    def __neg__(self):
        return Vector(-x for x in self)
    
    def __pos__(self):
        return Vector(self)
    
    def __add__(self, other):
        try:
            pairs = itertools.zip_longest(self, other, fillvalue=0.0)
            return Vector(a + b for a, b in pairs)
        except TypeError:
            return NotImplemented

    def __radd__(self, other):
        return self + other

    def __mul__(self, scalar):
        if isinstance(scalar, numbers.Real):
            return Vector(n * scalar for n in self)
        else:
            return NotImplemented
    
    def __rmul__(self, scalar):
        return self * scalar
    
    def __matmul__(self, other):
        try:
            return sum(a * b for a, b in zip(self, other))
        except TypeError:
            return NotImplemented
        
    def __rmatmul__(self, other):
        return self @ other
    
    def __bool__(self):
        return bool(abs(self))
    
    def __len__(self):
        return len(self._components)
    
    def __getitem__(self, index):
        cls = type(self)
        if isinstance(index, slice):
            return cls(self._components[index])
        elif isinstance(index, numbers.Integral):
            return self._components[index]
        else:
            msg = '{.__name__} indices must be integers'
            raise TypeError(msg.format(cls))
            
    shortcut_names = 'xyzt'
    
    def __getattr__(self, name):
        cls = type(self)
        if len(name) == 1:
            pos = cls.shortcut_names.find(name)
            if 0 <= pos < len(self._components):
                return self._components[pos]
        msg = '{.__name__!r} object has no atttribute {!r}'
        raise AttributeError(msg.format(cls, name))
        
    def __setattr__(self, name, value):
        cls = type(self)
        if len(name) == 1:
            if name in cls.shortcut_names:
                error = 'readonly attribute {attr_name!r}'
            elif name.islower():
                error = "can't set attributes 'a' to 'z' in {cls_name!r}"
            else:
                error = ''
            if error:
                msg = error.format(cls_name=cls.__name__, attr_name=name)
                raise AttributeError(msg)
        super().__setattr__(name, value)
    
    def angle(self, n):
        r = math.sqrt(sum(x * x for x in self[n:]))
        a = math.atan2(r, self[n-1])
        if (n == len(self) - 1) and (self[-1] < 0):
            return math.pi * 2 - a
        else:
            return a
        
    def angles(self):
        return (self.angle(n) for n in range(1, len(self)))
    
    def __format__(self, fmt_spec=''):
        if fmt_spec.endswith('h'): # hyperspherical coordinates
            fmt_spec = fmt_spec[:-1]
            coords = itertools.chain([abs(self)], self.angles())
            outer_fmt = '<{}>'
        else:
            coords = self
            outer_fmt = '({})'
        components = (format(c, fmt_spec) for c in coords)
        return outer_fmt.format(', '.join(components))
        
    @classmethod
    def frombytes(cls, octets):
        typecode = chr(octets[0])
        memv = memoryview(octets[1:]).cast(typecode)
        return cls(memv)

In [13]:
v1 = Vector([3, 4, 5])
v2 = Vector([6, 7, 8])
v1 + v2


Out[13]:
Vector([9.0, 11.0, 13.0])

In [14]:
v1 + v2 == Vector([3+6, 4+7, 5+8])


Out[14]:
True

In [15]:
v1 + (10, 20, 30)


Out[15]:
Vector([13.0, 24.0, 35.0])

In [16]:
from vector2d_v3 import Vector2d

In [17]:
v2d = Vector2d(1, 2)

In [18]:
v1 + v2d


Out[18]:
Vector([4.0, 6.0, 5.0])

In [19]:
(10, 20, 30) + v1


Out[19]:
Vector([13.0, 24.0, 35.0])

In [20]:
v2d + v1


Out[20]:
Vector([4.0, 6.0, 5.0])

In [21]:
v1 + 1


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-76c8c91eaf2e> in <module>()
----> 1 v1 + 1

TypeError: unsupported operand type(s) for +: 'Vector' and 'int'

In [22]:
v1 + 'ABC'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-30e5276cebc2> in <module>()
----> 1 v1 + 'ABC'

TypeError: unsupported operand type(s) for +: 'Vector' and 'str'

Overloading * for Scalar Multiplication


In [28]:
v1 = Vector([1, 2, 3])

In [29]:
v1 * 10


Out[29]:
Vector([10.0, 20.0, 30.0])

In [31]:
v1 = Vector([1.0, 2.0, 3.0])

In [32]:
14 * v1


Out[32]:
Vector([14.0, 28.0, 42.0])

In [33]:
v1 * True


Out[33]:
Vector([1.0, 2.0, 3.0])

In [34]:
from fractions import Fraction

In [35]:
v1 * Fraction(1, 3)


Out[35]:
Vector([0.3333333333333333, 0.6666666666666666, 1.0])

THE NEW @ INFIX OPERATOR IN PYTHON 3.5


In [2]:
va = Vector([1, 2, 3])
vz = Vector([5, 6, 7])

In [4]:
va @ vz == 38.0


Out[4]:
True

In [5]:
[10, 20, 30] @ vz


Out[5]:
380.0

In [6]:
va @ 3


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-9dd52ac6de9c> in <module>()
----> 1 va @ 3

TypeError: unsupported operand type(s) for @: 'Vector' and 'int'

Rich Comparison Operators


In [8]:
va = Vector([1.0, 2.0, 3.0])
vb = Vector(range(1, 4))
va == vb


Out[8]:
True

In [9]:
vc = Vector([1, 2])
from vector2d_v3 import Vector2d
v2d = Vector2d(1, 2)
vc == v2d


Out[9]:
True

In [10]:
t3 = (1, 2, 3)
va == t3


Out[10]:
False

In [11]:
va != vb


Out[11]:
False

In [12]:
vc != v2d


Out[12]:
False

In [13]:
va != (1, 2, 3)


Out[13]:
True

Augmented Assignment Operators


In [2]:
v1 = Vector([1, 2, 3])

In [3]:
v1_alias = v1

In [5]:
id(v1)


Out[5]:
4371508360

In [6]:
v1 += Vector([4, 5, 6])

In [7]:
v1


Out[7]:
Vector([5.0, 7.0, 9.0])

In [8]:
id(v1)


Out[8]:
4371477840

In [9]:
v1_alias


Out[9]:
Vector([1.0, 2.0, 3.0])

In [10]:
v1 *= 11

In [11]:
v1


Out[11]:
Vector([55.0, 77.0, 99.0])

In [12]:
id(v1)


Out[12]:
4371478680

In [14]:
import abc

class Tombola(abc.ABC):
    
    @abc.abstractmethod
    def load(self, iterable):
        """Add items from an iterable"""
        
    @abc.abstractmethod
    def pick(self):
        """Remove item at random, returning it
        
        This method should raise 'LookupError' when the instance is empty.
        """
        
    def loaded(self):
        """Return 'True' if there's at least 1 item, 'False' otherwise."""
        return bool(self.inspect())
    
    def inspect(self):
        """Return a sorted tuple with the items currently inside."""
        items = []
        while True:
            try:
                items.append(self.pick())
            except LookupError:
                break
        self.load(items)
        return tuple(sorted(items))

In [15]:
import random

class BingoCage(Tombola):
    
    def __init__(self, items):
        self._randomizer = random.SystemRandom()
        self._items = []
        self.load(items)
        
    def load(self, items):
        self._items.extend(items)
        self._randomizer.shuffle(self._items)
        
    def pick(self):
        try:
            return self._items.pop()
        except IndexError:
            raise LookupError('pick from empty BingoCage')
            
    def __call__(self):
        self.pick()

In [16]:
import itertools

class AddableBingoCage(BingoCage):
    def __add__(self, other):
        if isinstance(other, Tombola):
            return AddableBingoCage(self.inspect() + other.inspect())
        else:
            return NotImplemented
        
    def __iadd__(self, other):
        if isinstance(other, Tombola):
            other_iterable = other.inspect()
        else:
            try:
                other_iterable = iter(other)
            except TypeError:
                self_cls = type(self).__name__
                msg = "right operand in += must be {!r} or an iterable"
                raise TypeError(msg.format(self_cls))
        self.load(other_iterable)
        return self

In [17]:
vowels = 'AEIOU'
globe = AddableBingoCage(vowels)
globe.inspect()


Out[17]:
('A', 'E', 'I', 'O', 'U')

In [18]:
globe.pick() in vowels


Out[18]:
True

In [19]:
len(globe.inspect())


Out[19]:
4

In [20]:
globe2 = AddableBingoCage('XYZ')
globe3 = globe + globe2

In [21]:
len(globe3.inspect())


Out[21]:
7

In [22]:
void = globe + [10, 20]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-af411a756e83> in <module>()
----> 1 void = globe + [10, 20]

TypeError: unsupported operand type(s) for +: 'AddableBingoCage' and 'list'

In [23]:
globe_orig = globe
len(globe.inspect())


Out[23]:
4

In [24]:
globe += globe2
len(globe.inspect())


Out[24]:
7

In [25]:
globe += ['M','N']
len(globe.inspect())


Out[25]:
9

In [26]:
globe is globe_orig


Out[26]:
True

In [27]:
globe += 1


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-c6ec4d97e758> in __iadd__(self, other)
     14             try:
---> 15                 other_iterable = iter(other)
     16             except TypeError:

TypeError: 'int' object is not iterable

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-27-f0e1c411856a> in <module>()
----> 1 globe += 1

<ipython-input-16-c6ec4d97e758> in __iadd__(self, other)
     17                 self_cls = type(self).__name__
     18                 msg = "right operand in += must be {!r} or an iterable"
---> 19                 raise TypeError(msg.format(self_cls))
     20         self.load(other_iterable)
     21         return self

TypeError: right operand in += must be 'AddableBingoCage' or an iterable

In [ ]: